package models

import (
	"github.com/astaxie/beego/orm"
	"strconv"
	"time"
)

type LinksModels struct{}

type Link struct {
	Link_id int    `orm:"pk;auto;size(8)"`
	Name    string `orm:"size(50);default('')"`
	Url     string `orm:"size(255);default('')"`
	Type_id int    `orm:"size(8)"`
	Qq      string `orm:"size(20);default('')"`
	Sort    int    `orm:"size(8);default(10)"`
	Addtime int64  `orm:"size(11);default(0)"`
	Open    int    `orm:"size(1);default(0)"`
}

func init() {
	orm.RegisterModel(new(Link))
}

func (m *LinksModels) Get(id int) (Link, error) {
	link := Link{Link_id: id}
	o := orm.NewOrm()
	err := o.Read(&link)
	return link, err
}

func (m *LinksModels) Query() ([]Link, error) {
	var list []Link
	o := orm.NewOrm()
	_, err := o.QueryTable("link").All(&list)
	return list, err
}

func (m *LinksModels) Insert(maps map[string]interface{}) (int64, error) {
	link := Link{}
	if maps["name"] != nil {
		link.Name = maps["name"].(string)
	}
	if maps["url"] != nil {
		link.Url = maps["url"].(string)
	}
	if maps["qq"] != nil {
		link.Qq = maps["qq"].(string)
	}
	if maps["type_id"] != nil {
		link.Type_id, _ = strconv.Atoi(maps["type_id"].(string))
	}
	if maps["sort"] != nil {
		link.Sort, _ = strconv.Atoi(maps["sort"].(string))
	}
	if maps["open"] != nil {
		link.Open, _ = strconv.Atoi(maps["open"].(string))
	}
	link.Addtime = time.Now().Unix()
	o := orm.NewOrm()
	return o.Insert(&link)
}

func (m *LinksModels) Update(maps map[string]interface{}) (int64, error) {
	link := Link{}
	link.Link_id, _ = strconv.Atoi(maps["link_id"].(string))
	o := orm.NewOrm()
	_ = o.Read(&link)
	if maps["name"] != nil {
		link.Name = maps["name"].(string)
	}
	if maps["url"] != nil {
		link.Url = maps["url"].(string)
	}
	if maps["qq"] != nil {
		link.Qq = maps["qq"].(string)
	}
	if maps["type_id"] != nil {
		link.Type_id, _ = strconv.Atoi(maps["type_id"].(string))
	}
	if maps["sort"] != nil {
		link.Sort, _ = strconv.Atoi(maps["sort"].(string))
	}
	if maps["open"] != nil {
		link.Open, _ = strconv.Atoi(maps["open"].(string))
	}
	return o.Update(&link)
}

func (m *LinksModels) Delete(id int) (int64, error) {
	o := orm.NewOrm()
	return o.Delete(&Link{Link_id: id})
}
